require 'yaml'
require 'sanitize'
require 'wolfram'

module TdBerlinTest
  class WolframApiFetcher
    WOLFRAM_APP_ID = 'Q6LH5Y-3JA7L335LL'

    attr_accessor :language_data, :result

    def initialize(yaml_file)
      @language_data = parse_yaml_file(yaml_file)
      @result_array = []
      Wolfram.appid = WOLFRAM_APP_ID
    end

    def parse_yaml_file(yaml_file)
      YAML.load_file(yaml_file)
    end

    def run
      @language_data[0]['langs'].each do |language|
        fetch_wolfram(language)
      end

      output_result_as_array
    end

    def fetch_wolfram(language)
      options = {:assumption => "*C.#{language}-_*ProgrammingLanguage-" }

      @currently_fetched_language = language

      result = Wolfram.fetch(language, options)

      get_influence_data_from_result(result)
    end

    def get_influence_data_from_result(result)
      related_languages_url = result.xml.xpath('//queryresult').attr('related').to_s

      fetch_wolfram_for_related_languages_data(related_languages_url)
    end

    def fetch_wolfram_for_related_languages_data(url)
      response_xml = open(url).read

      related_languages = Nokogiri::XML(response_xml).search('relatedquery')

      related_languages.each do |related_language|
        filter_out_influenced_language(related_language)
      end
    end

    def filter_out_influenced_language(related_language)
      # strip out the <relatedquery> tags
      related_language = Sanitize.clean(related_language.to_s)

      matches = related_language.scan(/(\S+)(?=\sprogramming language)/i)

      if !matches.empty?
        programming_language = matches[0][0]

        @currently_fetched_language[0] = @currently_fetched_language[0].capitalize

        if programming_language != @currently_fetched_language
          @result_array.push(programming_language)
        end
      end
    end

    def output_result_as_array
      puts ("['" + @result_array.join("','") + "']")
    end
  end
end